import os.path
import sys

"""
功能：将TJpgConvert取模后的代码再解析为jpg图片
"""


def parse_code_file(file_path):
    list = []
    with open(file_path, "r") as file:
        lines = file.readlines()
        print(lines)
        for line in lines:
            print(line)
            if line.startswith("//"):
                continue
            if not line.__contains__("0x"):
                continue
            arr = line.split(",")
            print(arr)
            for hex in arr:
                print(hex)
                if hex.__contains__("0x"):
                    i = int(hex, 16)
                    list.append(i.to_bytes(1, "little"))
    return list


def write_image_file(file_path, file_data):
    with open(file_path, "wb") as file:
        for b in file_data:
            file.write(b)

# 测试
# data = parse_code_file("test1.h")
# print(data)
# write_image_file("test.jpg", data)

if __name__ == '__main__':
    print("代码转换为图片")
    print(sys.argv)
    if len(sys.argv) < 2:
        print("用法: 把要转换的 .h 文件拖到.exe图标上即可")
        exit(0)

    for i, img_path in enumerate(sys.argv[1:]):
        fileName = os.path.basename(img_path)
        print("正在转换图片[{}] ...".format(fileName))
        data = parse_code_file(img_path)
        print(data)
        name = os.path.splitext(fileName)[0]
        write_image_file(f"{name}.jpg", data)
